<script setup>
import wInput from '../../components/watch-input.vue' //input
import wButton from '../../components/watch-button.vue' //button
import { getOpenIdApi, userRegisterApi,getUserByIdApi } from '@/apis/user.js'
import { useUserStore } from '@/stores/userStore.js'
import { nextTick, onMounted, ref } from 'vue';
const showAgree = ref(false);
const userStore = useUserStore();
const userInfo = ref({
	userId: '',//用户id
	avatarUrl: '',//头像
	phone: '', //电话
	password: '', //密码
	userName: '',//昵称
	gender: '',//性别
})

const loginParams = ref({
	"appid": "wxf3f4ec422cad1890",
	"secret": "db5fdb593615ddfff0d2e89474ea6a3d",
	"code": "",
	"grant_type": "authorization_code"
})

onMounted(async () => {
	loginParams.value.code = (await uni.login()).code
	const getOpenId = await getOpenIdApi(loginParams.value)
	const userRes = await getUserByIdApi({'userId':getOpenId.openid})
	if (userRes.code === 200) {
		uni.showToast({
			title: '该用户已经注册',
			icon: 'error', // 可以设置为'success'、'loading'等
			duration: 1000 // 提示框停留时间，单位毫秒
		});

		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}, 300); // 等待提示框显示完毕后再执行跳转
		
	} else {
		userInfo.value.userId = getOpenId.openid;
	uni.showModal({
		title: '温馨提示',
		content: '亲，授权微信登录后才能正常使用小程序功能',
		success: (res) => {
			if (res.confirm) {
				uni.getUserProfile({ desc: '获取你的昵称、头像及性别' }).then((res) => {
					userInfo.value.userName = res.userInfo.nickName
					if (res.userInfo.gender === 0) {
						userInfo.value.gender = '未知'
					}
					if (res.userInfo.gender === 1) {
						userInfo.value.gender = '男'
					}
					if (res.userInfo.gender === 2) {
						userInfo.value.gender = '女'
					}
					userInfo.value.avatarUrl = res.userInfo.avatarUrl
					showAgree.value = true
				
				})
			} else {
				uni.showToast({
					title: '请同意《用户协议》',
					icon: 'none',
					position: 'bottom',
					duration: 1000
				});
			}
		},
		fail: () => {
			uni.showToast({
				title: '发生未知异常',
				icon: 'error', // 可以设置为'success'、'loading'等
				duration: 1000 // 提示框停留时间，单位毫秒
			})
		}
	})
	}
})

const isShowAgree = () => {
	showAgree.value = !showAgree.value
	if (showAgree.value) {
		uni.showModal({
			title: '温馨提示',
			content: '亲，授权微信登录后才能正常使用小程序功能',
			success: (res) => {
				if (res.confirm) {
					uni.getUserProfile({ desc: '获取你的昵称、头像及性别' }).then((res) => {
						userInfo.value.userName = res.userInfo.nickName
						if (res.userInfo.gender === 0) {
							userInfo.value.gender = '未知'
						}
						if (res.userInfo.gender === 1) {
							userInfo.value.gender = '男'
						}
						if (res.userInfo.gender === 2) {
							userInfo.value.gender = '女'
						}
						userInfo.value.avatarUrl = res.userInfo.avatarUrl
					})
				} else {
					uni.showToast({
						title: '请同意《用户协议》',
						icon: 'none',
						position: 'bottom',
						duration: 1000
					})
				}
			},
			fail: () => {
				uni.showToast({
					title: '发生未知异常',
					icon: 'error', // 可以设置为'success'、'loading'等
					duration: 1000 // 提示框停留时间，单位毫秒
				});
			}
		})
	}
}
const register = async () => {
	if (showAgree.value) {
		// 进行注册
		const res = await userRegisterApi(userInfo.value)
		if(res.code === 200){
			userStore.setUserInfo(res.data)
			uni.showToast({
				title: res.msg,
				icon: 'success',
				duration: 1000
			});
		}else{
			uni.showToast({
				title: res.msg,
				icon: 'error',
				duration: 1000
			});
		}
		setTimeout(() => {
			uni.navigateBack()
		}, 1100);
	
	} else {
		uni.showToast({
			title: '请同意《用户协议》',
			icon: 'none',
			position: 'bottom',
			duration: 1000
		})
	}
}

// getVerCode(){
// 	//获取验证码
// 	if (_this.userInfo.value.phone.length != 11) {
// 	     uni.showToast({
// 	        icon: 'none',
// 			position: 'bottom',
// 	        title: '手机号不正确'
// 	    });
// 	    return false;
// 	}
// 	console.log("获取验证码")
// 	this.$refs.runCode.$emit('runCode'); //触发倒计时（一般用于请求成功验证码后调用）
// 	uni.showToast({
// 	    icon: 'none',
// 		position: 'bottom',
// 	    title: '模拟倒计时触发'
// 	});

// 	setTimeout(function(){
// 		_this.$refs.runCode.$emit('runCode',0); //假装模拟下需要 终止倒计时
// 		uni.showToast({
// 		    icon: 'none',
// 			position: 'bottom',
// 		    title: '模拟倒计时终止'
// 		});
// 	},3000)
// },
// startReg() {
// 	//注册
// 	if(this.isRotate){
// 		//判断是否加载中，避免重复点击请求
// 		return false;
// 	}
// 	if (this.showAgree == false) {
// 	    uni.showToast({
// 	        icon: 'none',
// 			position: 'bottom',
// 	        title: '请先同意《协议》'
// 	    });
// 	    return false;
// 	}
// 	if (this.userInfo.value.phone.length !=11) {
// 	    uni.showToast({
// 	        icon: 'none',
// 			position: 'bottom',
// 	        title: '手机号不正确'
// 	    });
// 	    return false;
// 	}
//     if (this.userInfo.value.password.length < 6) {
//         uni.showToast({
//             icon: 'none',
// 			position: 'bottom',
//             title: '密码不正确'
//         });
//         return false;
//     }
// 	if (this.verCode.length != 4) {
// 	    uni.showToast({
// 	        icon: 'none',
// 			position: 'bottom',
// 	        title: '验证码不正确'
// 	    });
// 	    return false;
// 	}
// 	console.log("注册成功")
// 	_this.isRotate=true
// 	setTimeout(function(){
// 		_this.isRotate=false
// 	},3000)
// }
const iconClick = () => {
	userInfo.value.phone = ''
}
</script>

<template>
	<view class="register">

		<view class="content">
			<!-- 头部logo -->
			<view class="header">
				<image :src="userInfo.avatarUrl"></image>
			</view>
			<!-- 主体 -->
			<view class="main">
				<div class="main-list">
					<uni-easyinput class="main-input" suffixIcon="clear" v-model="userInfo.phone" placeholder="请输入手机号码"
					@iconClick="iconClick"></uni-easyinput>
				</div>
				<div class="main-list">
					<uni-easyinput class="main-input" type="password" v-model="userInfo.password" placeholder="请输入密码"></uni-easyinput>
				</div>
			</view>

			<wButton class="wbutton" text="注 册" :rotate="isRotate" @click.native="register"></wButton>

			<!-- 底部信息 -->
			<view class="footer">
				<text @tap="isShowAgree" class="cuIcon" :class="showAgree ? 'cuIcon-radiobox' : 'cuIcon-round'">
					同意获取用户信息</text>
				<!-- 协议地址 -->
				<navigator url="" open-type="navigate">《协议》</navigator>
			</view>
		</view>
	</view>
</template>

<style>
@import url("../../components/css/icon.css");
@import url("./css/main.css");

.main-list{
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		/* height: 36rpx; */   /* Input 高度 */
		color: #333333;
		padding: 0rpx 32rpx;
		margin:32rpx 0;
	}
	.main-input{
		flex: 1;
		text-align: left;
		font-size: 28rpx;
		/* line-height: 100rpx; */
		padding-right: 10rpx;
		margin-left: 20rpx;
	}
</style>